package com.ominext.facebook;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import com.ominext.beautifulcapture.R;
import com.ominext.home.HomeActivity;
import com.ominext.home.Path;

public class HomeFacebook extends Activity {

	private static String APP_ID = "704526069576010";
	public String NAME_FB;
	public String EMAIL_FB;
	public String USER_ID;
	// Instance of Facebook Class
	public Facebook facebook = new Facebook(APP_ID);
	public AsyncFacebookRunner mAsyncRunner;
	String FILENAME = "AndroidSSO_data";
	public SharedPreferences mPrefs;

	// Buttons
	Button mButtonUpload;
	Button mButtonCancel;
	Button mButtonLogout;
	Button mUser;

	// ImageView
	ImageView mImage;
	ImageView mUserPicture;
	// EditText
	EditText mStatus;

	// TextView

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.upload_photo);
		mImage = (ImageView) findViewById(R.id.imageViewUpload);
		mStatus = (EditText) findViewById(R.id.status_photo);
		mButtonUpload = (Button) findViewById(R.id.up_to_fb);
		mButtonCancel = (Button) findViewById(R.id.cancel);
		mUser = (Button) findViewById(R.id.user_fb);
		mButtonLogout = (Button) findViewById(R.id.logout_fb);
		mAsyncRunner = new AsyncFacebookRunner(facebook);
		// mUserPicture = (ImageView)findViewById(R.id.image_user);
		loginToFacebook();

		getProfileInformation();

		mButtonLogout.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// logoutFromFacebook();
				fb_Logout();
				Intent intent = new Intent(HomeFacebook.this,
						HomeActivity.class);
				startActivity(intent);
			}
		});
		mButtonUpload.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				UploadPhoto();
			}
		});
		mButtonCancel.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(HomeFacebook.this,
						HomeActivity.class);
				startActivity(intent);
			}
		});

	}

	/**
	 * Function to login into facebook
	 * */
	@SuppressWarnings("deprecation")
	public void loginToFacebook() {

		mPrefs = getPreferences(MODE_PRIVATE);
		String access_token = mPrefs.getString("access_token", null);
		long expires = mPrefs.getLong("access_expires", 0);
		if (access_token != null) {

			facebook.setAccessToken(access_token);
			// mUser.setText("Hello" + NAME_FB);
			mUser.setVisibility(View.VISIBLE);
			mButtonLogout.setVisibility(View.VISIBLE);
			mStatus.setVisibility(View.VISIBLE);
			mImage.setVisibility(View.VISIBLE);
			mImage.setImageBitmap(BitmapFactory.decodeFile(Path.imageShowPath));
			mButtonUpload.setVisibility(View.VISIBLE);
			mButtonCancel.setVisibility(View.VISIBLE);
			Log.d("FB Sessions", "" + facebook.isSessionValid());

		}

		if (expires != 0) {
			facebook.setAccessExpires(expires);
		}

		if (!facebook.isSessionValid()) {
			facebook.authorize(this,
					new String[] { "email", "publish_stream" },
					new DialogListener() {

						@Override
						public void onCancel() {
							// Function to handle cancel event
						}

						@Override
						public void onComplete(Bundle values) {
							// Function to handle complete event
							// Edit Preferences and update facebook acess_token
							SharedPreferences.Editor editor = mPrefs.edit();
							editor.putString("access_token",
									facebook.getAccessToken());
							editor.putLong("access_expires",
									facebook.getAccessExpires());
							editor.commit();
							mUser.setVisibility(View.VISIBLE);
							mButtonLogout.setVisibility(View.VISIBLE);
							mStatus.setVisibility(View.VISIBLE);
							mImage.setVisibility(View.VISIBLE);
							mImage.setImageBitmap(BitmapFactory
									.decodeFile(Path.imageShowPath));
							mButtonUpload.setVisibility(View.VISIBLE);
							mButtonCancel.setVisibility(View.VISIBLE);
						}

						@Override
						public void onError(DialogError error) {
							// Function to handle error

						}

						@Override
						public void onFacebookError(FacebookError fberror) {
							// Function to handle Facebook errors

						}

					});
		}

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		facebook.authorizeCallback(requestCode, resultCode, data);
	}

	@SuppressWarnings("deprecation")
	public void getProfileInformation() {
		mAsyncRunner.request("me", new RequestListener() {
			@Override
			public void onComplete(String response, Object state) {
				Log.d("Profile", response);
				String json = response;
				try {
					// Facebook Profile JSON data
					JSONObject profile = new JSONObject(json);

					// getting name of the user
					final String name = profile.getString("name");
					// getting email of the user
					final String email = profile.getString("email");

					USER_ID = profile.getString("id");
					URL img_value = null;
					try {
						img_value = new URL("http://graph.facebook.com/"
								+ USER_ID + "/picture?type=large");
					} catch (MalformedURLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					// Bitmap mIcon1 = null;
					// try {
					// mIcon1 =
					// BitmapFactory.decodeStream(img_value.openConnection().getInputStream());
					// } catch (IOException e) {
					// // TODO Auto-generated catch block
					// e.printStackTrace();
					// }

					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							// mUserPicture.setImageBitmap(mIcon1);
							mUser.setText("Hello " + name + "!");
							Toast.makeText(getApplicationContext(),
									"Name: " + name + "\nEmail: " + email,
									Toast.LENGTH_LONG).show();
						}

					});

				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onIOException(IOException e, Object state) {
			}

			@Override
			public void onFileNotFoundException(FileNotFoundException e,
					Object state) {
			}

			@Override
			public void onMalformedURLException(MalformedURLException e,
					Object state) {
			}

			@Override
			public void onFacebookError(FacebookError e, Object state) {
			}
		});
	}

	/**
	 * Function to Logout user from Facebook
	 * */
	@SuppressWarnings("deprecation")
	public void logoutFromFacebook() {
		mPrefs.edit().remove("text").commit();
		SharedPreferences.Editor editor = mPrefs.edit();
		editor.clear();
		mAsyncRunner.logout(this, new RequestListener() {
			@Override
			public void onComplete(String response, Object state) {
				Log.d("Logout from Facebook", response);
				if (Boolean.parseBoolean(response) == true) {
					runOnUiThread(new Runnable() {

						@Override
						public void run() {

						}

					});

				}

			}

			@Override
			public void onIOException(IOException e, Object state) {
			}

			@Override
			public void onFileNotFoundException(FileNotFoundException e,
					Object state) {
			}

			@Override
			public void onMalformedURLException(MalformedURLException e,
					Object state) {
			}

			@Override
			public void onFacebookError(FacebookError e, Object state) {
			}
		});
	}

	public boolean fb_Logout() {

		Toast.makeText(getApplicationContext(),
				"You are logged out from Facebook.", Toast.LENGTH_LONG).show();
		mPrefs.edit().clear().commit();
		SharedPreferences.Editor editor = mPrefs.edit();

		try {
			Log.d("Tests", "Testing logout");
			String response = facebook.logout(this);
			if (!response.equals("true")) {
				return false;
			}
			Log.d("Tests", "Testing logout on logged out facebook session");
			try {
				Util.parseJson(facebook.logout(this));
				return false;
			} catch (FacebookError e) {
				if (e.getErrorCode() != 101
						|| !e.getMessage().equals("Invalid API key")) {
					return false;
				}
			}
			try {
				Util.parseJson(new Facebook(APP_ID).logout(this));
				return false;
			} catch (FacebookError e) {
				if (e.getErrorCode() != 101
						|| !e.getMessage().equals("Invalid API key")) {
					return false;
				}
			}
			return true;
		} catch (Throwable e) {
			e.printStackTrace();
			return false;
		}

	}

	// upload photo
	public void UploadPhoto() {
		Bundle params = new Bundle();
		params.putString("method", "photos.upload");
		params.putString("app_id", "704526069576010");
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inScaled = false;
		Bitmap b = BitmapFactory.decodeFile(Path.imageShowPath);
		byte[] data = null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		b.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		data = baos.toByteArray();
		String status = "";
		status = mStatus.getText().toString();

		if (data != null) {
			params.putByteArray("picture", data);
			params.putString("caption", status);

			mAsyncRunner.request(null, params, "POST",
					new SampleUploadListener(), null);
			Toast.makeText(getApplicationContext(), "uploading....",
					Toast.LENGTH_LONG).show();

			Log.e("PHOTOUPLOAD", "Attemping an upload...");
		}

	}

}
